package cn.phub.org.service.impl;


import cn.phub.basic.service.impl.BaseServiceImpl;
import cn.phub.basic.util.MD5Utils;
import cn.phub.basic.util.StrUtils;
import cn.phub.org.domain.Employee;
import cn.phub.org.mapper.EmployeeMapper;
import cn.phub.org.service.IEmployeeService;
import cn.phub.user.domain.Logininfo;
import cn.phub.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


/**
 * 员工服务实现类
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    //1.基础的CRUD的实现 通过继承BaseServiceImpl得到

    //2.特定的实现，在这里自己写
    @Override
    public void add(Employee employee) {
        initEmployee(employee);
        Logininfo logininfo = employee2Logininfo(employee);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        employeeMapper.save(employee);
        initRelationTable(employee);
    }

    private void initRelationTable(Employee employee) {
        //移除历史数据
        employeeMapper.removeEmployeeRole(employee.getId());
        //保留所有
        employeeMapper.addEmployeeRole(employee.getId(),employee.getRoles());
    }

    private Logininfo employee2Logininfo(Employee employee) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        //一定要手动设置
        logininfo.setType(0);
        return logininfo;
    }

    private void initEmployee(Employee employee){
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }

    @Override
    public void update(Employee employee) {
        super.update(employee);
    }

    @Override
    public void remove(Long id) {
        super.remove(id);
    }

    /**
     * 根据登录人ID查询员工
     * @param id
     * @return
     */
    @Override
    public Employee loadByLoginInfoId(Long id) {
        return employeeMapper.loadByLoginInfoId(id);
    }
}
